package com.hdax.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;


import lombok.extern.slf4j.Slf4j;


/**
 * 登录控制器
 *
 * @author Aizen
 * @date 2022/05/04
 */
@Controller
@RequestMapping(path = "/user")
@Slf4j
public class LoginController{

	/**
	 * 跳转至登录页面
	 *
	 * @return {@link ModelAndView}
	 */
	@GetMapping("/login")
	public ModelAndView login() {
		return new ModelAndView("login");
	}

	/**
	 * 登录
	 *
	 * @param username 用户名
	 * @param password 密码
	 * @param model    模型
	 * @return {@link String}
	 */
	@PostMapping("/login")
	public String login(String username,String password,Model model){
		//获取当前的用户
		Subject subject = SecurityUtils.getSubject();
		//封装用户的登录数据
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try{//执行登录的方法，如果没有异常就说明ok
			subject.login(token);
			return "/index";
		}catch (UnknownAccountException e){//用户名不存在
			model.addAttribute("msg","用户名错误");
			return "login";
		}catch (IncorrectCredentialsException e){ //密码不存在
			model.addAttribute("msg","密码错误");
			return "login";
		}catch (RuntimeException e) {
			model.addAttribute("msg","该用户已被禁用");
			System.out.println(e);
			return "login";
		}
	}


}
